<template>
  <Upload
    :with-credentials="true"
    :action="action"
    :on-remove="_deleteFile"
    :on-success="onSuccess"
    :on-preview="previewHandle"
    :on-exceeded-size="onExceededSize"
    :default-file-list="defaultFileList"
    :show-upload-list="showUploadList"
    :max-size="maxSize"
    :disabled="disabled"
    :name="name"
    :class="{disabled: disabled}"
    :before-upload="beforeUpload"
    :multiple="multiple"
  >
    <Button icon="ios-cloud-upload-outline">{{text}}</Button>
  </Upload>
</template>
<script>
// import Locale from "../mixins/locale";
// import { getHttpHeaders } from "../utils/http";

import { superviseInfoAPI } from "@api/superviseInfo";

export default {
  data() {
    // let headers = getHttpHeaders();
    return {
      text: '上传文件',
      action: this.servicePath,
      fileBuffer: []
    };
  },
  props: {
    value: { type: Array, default: () => [] },
    servicePath: String,
    showUploadList: { type: Boolean, default: true },
    multiple: { type: Boolean, default: true },
    maxSize: { type: Number, default: 1024 },
    name: { type: String, default: 'file' },
    disabled: { type: Boolean, default: false }
  },
  computed: {
    defaultFileList() {
/*      for (let item of this.value) {
        if (!item.name) {
          item.name = item.id;
        }
      }*/

      return this.value;
    }
  },
  mounted() {
    if(this.disabled) {
      const eles = document.querySelectorAll('.ivu-upload-list-remove')
      Array.prototype.forEach.call(eles, (item) => {
        item.style.display = 'none'
      })
    }
  },
  methods: {
    onSuccess(response, file, fileList) {
      this.$emit(
        "input",
        fileList.map(item => {
          let res = null
          if (item.response)  {
            if (typeof item.response.data === 'string') {
              res = JSON.parse(item.response.data)
            } else {
              res = item.response.data
            }
            return {
              name: item.name,
              key: res.length ? res[0].fileKey : ''
            }
          }
        })
      );
    },
    _deleteFile(fileInfo) {
      let fileId = fileInfo.id || fileInfo.response.data;
      this.$emit(
        "input",
        this.value
          .filter(item => item.id !== fileId)
          .map(item => ({
            name: item.name,
            id: item.id || item.response
          }))
      );
    },
    _downloadFile(fileInfo) {
      fileInfo.fileId = fileInfo.id || fileInfo.response;
      this.downloadFile(fileInfo);
    },
    onExceededSize(fileInfo) {
      this.fileBuffer.push(fileInfo);
      if (this.timer) {
        clearTimeout(this.timer);
      }

      this.timer = setTimeout(() => {
/*        this.$message.error({
          content: '单个文件大小不能超过50M，请检查',
          duration: 10,
          closable: true
        });*/
        this.$Modal.warning({
          title: '提示',
          content: '单个文件大小不能超过50M，请检查'
        });
        this.timer = null;
      }, 50);
    },
    beforeUpload(file) {
      const typeArr = ['image/jpeg', 'image/png', 'application/pdf', 'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      ]
      if (!typeArr.includes(file.type)) {
        // this.$message.error('只允许上传PDF、JPG、PNG、JPEG、DOC、DOCX、XLSX、XLS等文件类型')
        this.$Modal.error({
          title: '提示',
          content: '请上传PDF、JPG、PNG、JPEG、DOC、DOCX、XLSX、XLS类型文件！',
        });
        return false
      }
      console.log('length', this.value.length);
      if (this.value.length >= 20) {
        this.$Modal.warning({
          title: '提示',
          content: '每单不得超过20个附件'
        });
        return false
      }
    },
    previewHandle(file) {
      let fileKey = null
      let name = file.name
      if (file.key) {
        return superviseInfoAPI.getUploadFileUrl({ fileKey:file.key, name }).then(res => {
          window.open(res.data)
        })
      }
      if (typeof file.response.data === 'string') {
        fileKey =  JSON.parse(file.response.data)[0].fileKey
      } else {
        fileKey = file.response.data.fileKey
      }
      superviseInfoAPI.getUploadFileUrl({ fileKey, name }).then(res => {
        window.open(res.data)
      })
    }
  }
};
</script>
<style lang="less">
.ivu-upload-list {
  line-height: 1;
  span {
    line-height: 1.5;
  }
}
.ivu-upload.disabled .ivu-btn-default{
  cursor: not-allowed;
  background: #f3f3f3;
  color: #666F83;
  border: 1px solid #dddee1;
}
</style>

